package cn.yuanqiao.archive.chooesuser.service.impl;/**
 * @author 赵常飞
 * @date 2023/8/7 13:46
 */

import cn.yuanqiao.archive.chooesuser.domain.UserTree;
import cn.yuanqiao.archive.chooesuser.mapper.ChooseUserMapper;
import cn.yuanqiao.archive.chooesuser.service.IChooseUserService;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 *@AUTHOR:赵常飞
 *@date 2023/8/7 13:46
 */
@Service
public class ChooseUserServoceImpl implements IChooseUserService {

    @Autowired
    private ChooseUserMapper chooseUserMapper;

    @Override
    public List<UserTree> getusertree() {
        String tenantCode = SecurityUtils.getLoginUser().getUser().getTenantCode();
        Map<String,Object> rootmap = chooseUserMapper.getusertreeroot(0L);//获取根
        UserTree rootTree=new UserTree();
        rootTree.setId(0L);
        rootTree.setLabel((String) rootmap.get("DEPT_NAME"));
        rootTree.setType("t");
        rootTree.setChildren(getchildren(Long.parseLong(String.valueOf(rootmap.get("DEPT_ID"))),"t",tenantCode));
        List<UserTree> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;
    }

    private List<UserTree> getchildren(long id, String type,String tenantCode) {
        if(!"d".equals(type)&&!"t".equals(type)){
            return null;
        }else{
            List<Map<String,Object>> list = chooseUserMapper.getchildrens(id,tenantCode);
            List<UserTree> chilTrees = new ArrayList<>();
            for(Map map:list){
                UserTree chilTree = new UserTree();
                chilTree.setId(Long.parseLong(String.valueOf(map.get("USERID"))));
                chilTree.setLabel(String.valueOf(map.get("USERNAME")));
                chilTree.setType(String.valueOf(map.get("TYPE")));
                chilTree.setChildren(getchildren(Long.parseLong(String.valueOf(map.get("USERID"))),String.valueOf(map.get("TYPE")),tenantCode));
                chilTrees.add(chilTree);
            }
            return chilTrees;
        }
    }
}
